package org.zxyj.manage.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import org.zxyj.core.constants.Constants;
import org.zxyj.core.constants.Keys;
import org.zxyj.core.entity.Pagination;
import org.zxyj.core.entity.Result;
import org.zxyj.core.errorno.SystemErrorNo;
import org.zxyj.core.exception.ServiceException;
import org.zxyj.core.exception.UnifyException;
import org.zxyj.core.utils.FileUtil;
import org.zxyj.core.utils.MessageUtil;
import org.zxyj.core.web.controller.BaseController;
import org.zxyj.manage.entity.Template;
import org.zxyj.manage.service.ITemplateService;

/**
 * 扫描试卷模板下载
    * @ClassName: DownloadTemplateController
    * @Description: 扫描试卷模板下载
    * @author liuyong
    * @date 2016年6月23日
    *
 */
@Controller
@RequestMapping("/manage/downloadTemplate")
public class DownloadTemplateController extends BaseController {  
    @Autowired
    private ITemplateService templateService;
    //读取配置文件
    //private static PropertiesUtil configProp = PropertiesUtil.newInstance(Thread.currentThread().getContextClassLoader().getResource("").getPath() + "config/config.properties");
    
    @RequestMapping({"","/","/index"})
	public ModelAndView index(ModelAndView mv) {
		mv.setViewName(Views.LIST_VIEW);
		//List<Template> list = templateService.listEntities(null);
		//mv.addObject(Keys.KEY_PAGE_DATA, list);
		Pagination page = (Pagination) getRequestAttr("pagination");
		Pagination pagination = templateService.listEntities(null, page);
		mv.addObject(Keys.KEY_PAGINATION, pagination);
		return mv;
	}
    
    /**
     * 查询模板数据
        * @Title: getTempList
        * @param @param request
        * @param @param role
        * @param @return    参数
        * @return Result<?>    返回类型
        * @throws
     */
    @ResponseBody
    @RequestMapping("/getTempList")
	public Result<?> getTempList() {
		Result<List<Template>> result = new Result<List<Template>>();
		try {
			List<Template> list = templateService.listEntities(null);
			result.setData(list);
			result.setResultCode(Constants.Common.DEFAULT_RESULT_CODE);
		} catch (ServiceException e) {
			result.setResultCode(e.getErrorNo());
		}
		return result;
	}
    
    @RequestMapping("/add")
	public ModelAndView add(ModelAndView mv, Template entity) {
		mv.setViewName(Views.ADD_VIEW);
		mv.addObject(Keys.KEY_PARAM, entity);
		return mv;
	}
    
    @RequestMapping("/edit")
	public ModelAndView edit(ModelAndView mv, Template entity) {
		if (null == entity || null == entity.getId()) {
			throw new UnifyException(SystemErrorNo.DATA_NOT_EXIST);
		}
		mv.setViewName(Views.EDIT_VIEW);
		Map<String, Object> criteria = new HashMap<String, Object>();
		criteria.put("id", entity.getId());
		entity = templateService.findEntity(criteria);
		if (null == entity || null == entity.getId()) {
			throw new UnifyException(SystemErrorNo.DATA_NOT_EXIST);
		}
		mv.addObject(Keys.KEY_PARAM, entity);
		return mv;
	}
    
    @ResponseBody
	@RequestMapping("/edit/exec")
	public Result<?> doEdit(MultipartHttpServletRequest request, HttpServletResponse response,Template template) throws Exception {
    	Result<?> result = new Result<String>();
    	String fileDir = MessageUtil.getExtConfig("fj.template.url");//实际文件存放目录
    	//String filePath = request.getSession().getServletContext().getRealPath("/static/template"); //真实目录名  
        File file = new File(fileDir);
        if (!file.exists()){
            file.mkdirs();
        }
        
        String filePathOld = "";
        if (null != template.getId() && StringUtils.isNotEmpty(template.getId())) {
        	//编辑时查询记录原有文件
        	Map<String,Object> criteria = new HashMap<String,Object>();
        	criteria.put("id", template.getId());
            Template temp = templateService.findEntity(criteria);
            filePathOld = temp.getFilePath();
        }
        
		try {
			//保存文件
			List<MultipartFile> files = (List<MultipartFile>) request.getFiles("file");
			String filePath_ = "";
			String fileExtName = "";
			String fileUrl = "";
			//response.reset();
			//response.setContentType("text/html;charset=UTF-8");
			//PrintWriter writer = response.getWriter();
			for(MultipartFile ufile : files){
	            if (!ufile.isEmpty()) {
	            	fileExtName = "." + FileUtil.getExtName(ufile.getOriginalFilename());
	            	filePath_ = new Date().getTime() + fileExtName;
	            	fileUrl = fileDir + filePath_;
	                file = new File(fileUrl); //服务器上新建文件
	                try {
	                    FileUtils.copyInputStreamToFile(ufile.getInputStream(), file);
	    				//String json = "{\"imgurl\":\""+fileUrl+"\"}";  
	    			    //writer.write(json);
	    				//writer.close();
	                } catch (Exception e) {
	                    e.printStackTrace();
	                }
	            }
	        }
			
			template.setFilePath(filePath_);
			template.setFileType(fileExtName);
			this.templateService.saveOrUpdateEntity(template);
			//删除原有附件文件
			FileUtil.deleteFile(fileDir + filePathOld);
			result.setResultCode(Constants.Common.DEFAULT_RESULT_CODE);
		} catch (ServiceException e) {
			result.setResultCode(e.getErrorNo());
		}
		return result;
	}

	@ResponseBody
	@RequestMapping("/delete/exec")
	public Result<?> doDelete(Template template) {
		Result<?> result = new Result<String>();
		String fileDir = MessageUtil.getExtConfig("fj.template.url");//实际文件存放目录
		try {
			//查询记录原有文件
        	Map<String,Object> criteria = new HashMap<String,Object>();
        	criteria.put("id", template.getId());
            Template temp = templateService.findEntity(criteria);
            String filePathOld = temp.getFilePath();
            
			this.templateService.deleteEntity(criteria);
			//删除原有附件文件
			FileUtil.deleteFile(fileDir + filePathOld);
			result.setResultCode(Constants.Common.DEFAULT_RESULT_CODE);
		} catch (ServiceException e) {
			result.setResultCode(e.getErrorNo());
		}
		return result;
	}
	
    //文件下载
    @ResponseBody
    @RequestMapping("/download")
    public void downloadTemp(HttpServletRequest request,HttpServletResponse response) throws Exception{
    	//String contextPath = request.getSession().getServletContext().getRealPath("/static/template");
    	String fileDir = MessageUtil.getExtConfig("fj.template.url");//实际文件存放目录
    	Map<String,Object> criteria = new HashMap<String,Object>();
    	criteria.put("id", getParaValue("id"));
        Template temp = templateService.findEntity(criteria);
        String filePath = temp.getFilePath();
        String fileName = temp.getFileName();
        String fileType = temp.getFileType();
        filePath = fileDir + filePath;
        
        if (request.getHeader("User-Agent").toUpperCase().indexOf("MSIE") > 0) {  
            fileName = URLEncoder.encode(fileName, "UTF-8");  
        } else { 
            fileName = new String(fileName.getBytes("UTF-8"), "ISO8859-1");  
        }
        File file = new File(filePath);
        try {
            // 以流的形式下载文件。
            InputStream fis = new BufferedInputStream(new FileInputStream(file));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            // 清空response
            response.reset();
            // 设置response的Header
            response.addHeader("Content-Disposition", "attachment;filename=" + fileName+fileType);
            response.addHeader("Content-Length", "" + file.length());
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            toClient.write(buffer);
            toClient.flush();
            toClient.close();
        }
        catch (Exception e) { }
        finally {
            if (response.getOutputStream() != null) {
                response.getOutputStream().close();
            }
        }
    }
    
    /**
     * 校验文件是否存在
        * @Title: checkTemp
        * @param @throws UnsupportedEncodingException    参数
        * @return void    返回类型
        * @throws
     */
    @ResponseBody
    @RequestMapping("/checkTemp")
    public Result<?> checkTemp(HttpServletRequest request) throws UnsupportedEncodingException{
    	String contextPath = request.getSession().getServletContext().getRealPath("/static/template");
    	Result<?> result = new Result<String>();
    	String resultCode = Constants.Common.DEFAULT_RESULT_CODE;
    	try{
	    	Map<String,Object> criteria = new HashMap<String,Object>();
	    	criteria.put("id", getParaValue("id"));
	        Template temp = templateService.findEntity(criteria);
	        if(temp != null){
	            String filePath = temp.getFilePath();
	            if(StringUtils.isNotEmpty(filePath)){
	                filePath = contextPath+"/"+filePath;
	                //通过文件路径获得File对象
	                File file = new File(filePath);
	                if (!file.exists()) {
	                	resultCode = Constants.Common.FILE_NOT_EXISTS_RESULT_CODE;
	                }
	            }
	        }
        } catch (ServiceException e) {
			result.setResultCode(e.getErrorNo());
		}
    	result.setResultCode(resultCode);
        return result;
    }
    
    class Views {
		/**
		 * index视图
		 */
		public static final String LIST_INDEX = "/manage/template/list";
		
		/**
		 * 列表视图
		 */
		public static final String LIST_VIEW = "/manage/template/list";

		/**
		 * 添加视图
		 */
		public static final String ADD_VIEW = "/manage/template/edit";

		/**
		 * 编辑视图
		 */
		public static final String EDIT_VIEW = "/manage/template/edit";
	}
}
